package com.springboot.yu.projectinit.control.userinfo;

import com.springboot.yu.projectinit.bean.userinfo.UserInfoBean;
import com.springboot.yu.projectinit.service.userinfo.IUserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserinfoControl {
    @Autowired
    private IUserinfoService userinfoService;
    @RequestMapping("/UserInfoQueryById")
    public ResponseEntity<UserInfoBean> queryUserInfoById(Integer uid) {
        UserInfoBean userInfoBean = userinfoService.queryUserInfoById(uid);
        return new ResponseEntity<>(userInfoBean, HttpStatus.OK);
    }

    @RequestMapping("/UserInfoDeleteById")
    public ResponseEntity<Map<String, Object>> deleteUserInfoById(Integer uid) {
        // 调用service进行新增操作
        int i = userinfoService.deleteUserInfoById(uid);
        // 返回的结果集
        Map<String, Object> mapResult = new HashMap<>();
        // 记录结果条数
        mapResult.put("result", i);
        // 记录结果状态
        mapResult.put("msg", i == 1 ? "ok" : "ng");
        return new ResponseEntity<>(mapResult, HttpStatus.OK);
    }

    // 如果controller中的方法返回的是一个 ResponseEntity 类型的结果集，则自动进行ajax响应处理
    @RequestMapping("/UserInfoSave")
    public ResponseEntity<Map<String, Object>> doUserInfoSave(UserInfoBean userInfoBean) {
        // 调用service进行新增操作
        int i = userinfoService.saveOrUpdateUserInfo(userInfoBean);
        // 返回的结果集
        Map<String, Object> mapResult = new HashMap<>();
        // 记录结果条数
        mapResult.put("result", i);
        // 记录结果状态
        mapResult.put("msg", i == 1 ? "ok" : "ng");
        return new ResponseEntity<>(mapResult, HttpStatus.OK);
    }


    @RequestMapping("/login")
    public String doLogin(@RequestParam("username") String userName, @RequestParam("userpsw") String userPsw) {
        boolean result = userinfoService.doLogin(userName, userPsw);
        if(result) {
            return "logined/main";
        }else {
            return "index";
        }
    }

    @ResponseBody
    @RequestMapping("/UserinfoQuery")
    public List<UserInfoBean> doQuery(UserInfoBean userInfoBean) {
        return userinfoService.selectUser(userInfoBean);
    }
}
